<template>
  <el-select
    :value="value"
    :filter-method="selectFilter"
    :disabled="disabled"
    filterable
    placeholder="请选择"
    @visible-change="selectFilter"
  >
    <div v-if="type == 'id'">
      <el-option
        v-for="item in orgInfo"
        :key="item.ORG_ID"
        :label="item.ORG_NAME"
        :value="item.ORG_ID"
        @click.native="handelIndex(item.ORG_ID)"
      >
        <span style="float: left">{{ item.ORG_NAME }}</span>
        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.ORG_CODE }}</span>
      </el-option>
    </div>
    <div v-if="type == 'code'">
      <el-option
        v-for="item in orgInfo"
        :key="item.ORG_CODE"
        :label="item.ORG_NAME"
        :value="item.ORG_CODE"
        @click.native="handelIndex(item.ORG_CODE)"
      >
        <span style="float: left">{{ item.ORG_NAME }}</span>
        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.ORG_CODE }}</span>
      </el-option>
    </div>
  </el-select>
</template>

<script>
import selectComponents from '../Select/selectComponents'
import { getOrgsById } from '@/api/admin/org/deptInfo.js'
import { mapGetters } from 'vuex'

export default {
  name: 'BranchOrgSelect',
  mixins: [selectComponents],
  props: {
    type: {
      type: String,
      default: 'code'
    }
  },
  data() {
    return {
      orgInfo: [],
      selectOrgInfo: []
    }
  },
  computed: {
    ...mapGetters(['dictMap', 'regionMap', 'userInfo'])
  },
  created() {
    this.loadData()
  },
  methods: {
    loadData() {
      var id = this.userInfo.orgId
      getOrgsById(id).then(res => {
        this.orgInfo = res
        this.selectOrgInfo = res
      }).catch(err => {
        if (err) {
          console.log(err.stack)
        }
      })
    },
    selectFilter(val) {
      // 判断是否为空
      if (val) {
        if (val === true) { val = '' }
        // 同时筛选Lable与value的值
        this.orgInfo = this.selectOrgInfo.filter((item) => {
          if (!!~item.ORG_NAME.indexOf(val) || !!~item.ORG_NAME.toUpperCase().indexOf(val.toUpperCase()) || !!~item.ORG_CODE.indexOf(val) || !!~item.ORG_CODE.toUpperCase().indexOf(val.toUpperCase())) {
            return true
          }
        })
      } else {
        // 赋值还原
        this.orgInfo = this.selectOrgInfo
      }
    },
    handelIndex(code) {
      this.$emit('input', code)
    }
  }
}
</script>
